package com.practice.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.practice.blog.common.pojo.dataobject.BlogInfo;
import com.practice.blog.common.pojo.request.AddBlogParam;
import com.practice.blog.common.pojo.request.UpdateBlogParam;
import com.practice.blog.common.pojo.response.BlogInfoResponse;
import com.practice.blog.common.utils.BeanConver;
import com.practice.blog.mapper.BlogInfoMapper;
import com.practice.blog.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: hp
 * Date: 2025-01-30
 * Time: 13:14
 */
@Service
@Slf4j
public class BlogServiceImpl implements BlogService {
    @Autowired
    private BlogInfoMapper blogInfoMapper;

    @Override
    public List<BlogInfoResponse> getList() {
        List<BlogInfo> blogInfos = blogInfoMapper.selectList(new LambdaQueryWrapper<BlogInfo>()
                .eq(BlogInfo::getDeleteFlag, 0).orderByDesc(BlogInfo::getId));
        List<BlogInfoResponse> blogInfoResponse = blogInfos.stream().map(blogInfo -> BeanConver.trans(blogInfo))
                .collect(Collectors.toList());
        return blogInfoResponse;
    }

    @Override
    public BlogInfoResponse getBlogDetail(Integer blogId) {
        BlogInfo blogInfo = selectBlogById(blogId);
        return BeanConver.trans(blogInfo);
    }

    @Override
    public Boolean addBlog(AddBlogParam addBlogParam) {
        //将addBlogParam转成 BlogInfo
        BlogInfo blogInfo = BeanConver.trans(addBlogParam);
        try {
            int result = blogInfoMapper.insert(blogInfo);
            if(result == 1) {
                return true;
            }
        }catch (Exception e) {
            log.error("博客插入失败,e:{}",e);
        }
        return false;
    }

    @Override
    public Boolean updateBlog(UpdateBlogParam param) {
        BlogInfo blogInfo = BeanConver.trans(param);
        return update(blogInfo);
    }

    @Override
    public Boolean deleteBlog(Integer blogId) {
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setId(blogId);
        blogInfo.setDeleteFlag(1);
        return update(blogInfo);
    }

    public BlogInfo selectBlogById(Integer blogId) {
        return blogInfoMapper.selectOne(new LambdaQueryWrapper<BlogInfo>()
                .eq(BlogInfo::getId, blogId).eq(BlogInfo::getDeleteFlag, 0));
    }

    public Boolean update(BlogInfo blogInfo) {
        try {
            int result = blogInfoMapper.updateById(blogInfo);
            if(result == 1) {
                return true;
            }
        }catch (Exception e) {
            log.error("博客更新失败,e:{}",e);
        }
        return false;
    }
}
